package com.fengxiaoxiaoxi.fengutils.utils.email;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
@ConfigurationProperties(prefix = "spring.mail")
public class EmailUtils {

    private String username ;
    private String password ;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    @Autowired
    JavaMailSenderImpl javaMailSender;
    public boolean sendMimeMail(String sendEmail,String  subject,String text, File ... files)   {
        //封装简单的邮件内容
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //通过消息帮助对象来设置发送的内容 ,第二个参数为true表示可以发送附件
        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            //标题
            mimeMessageHelper.setSubject(subject);
            //第2个参数为true,才可以发送html代码
            mimeMessageHelper.setText(text, true);


            //如果有附件  则添加附件
            if (files.length!=0){
                for (int i = 0 ;i< files.length ; i++){


                    //发送附件  c.jpg 发送之后的文件名称 .
                    try {
                        mimeMessageHelper.addAttachment(files[i].getName(), files[i]);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return false ;
                    }


                }
            }
            //发送人
            mimeMessageHelper.setFrom(username);
            //收信人
            mimeMessageHelper.setTo(sendEmail);

            //发送邮件
            javaMailSender.send(mimeMessage);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }



        return false;
    }
}
